use axum::{
    extract::Query,
    routing::{get, post},
    Router,
};
use serde::Deserialize;

use crate::{
    serve::conn::{cbor_ok, online::ONLINE_INFO, Cbor, CborRet},
    store::vote_num,
};

#[derive(Deserialize)]
struct CreateReq {
    vote_id: i64,
    ty: u32,
    token: String,
}

async fn on_create(req: Cbor<CreateReq>) -> CborRet<i64> {
    let id = vote_num::create_with_debate(req.vote_id, req.ty, &req.token).await?;
    ONLINE_INFO.notify();
    cbor_ok(id)
}

#[derive(Deserialize)]
struct CountReq {
    vote_id: i64,
    ty: u32,
}

async fn on_count(req: Query<CountReq>) -> CborRet<i64> {
    let count = vote_num::count(req.vote_id, req.ty).await?;
    cbor_ok(count)
}

async fn on_query_vote_id() -> CborRet<Vec<i64>> {
    let ids = vote_num::vote_ids().await?;
    cbor_ok(ids)
}

pub fn register() -> Router {
    Router::new()
        .route("/create", post(on_create))
        .route("/count", get(on_count))
        .route("/vote_id", get(on_query_vote_id))
}
